﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Lion.WeiXin.Core.Data;
using Lion.WeiXin.Core.Models;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using Lion.WeiXin.Tools.Log;
using System.Web.Security;
namespace Lion.WeiXin.Controllers
{
      [PermissionFilter]
    public class EmployeeController : Controller
    {
        IEmployee idao = new EmployeeDAO();
        IRole irole = new RoleDAO();
        public ActionResult Index()
        {
            return View();
        }

        /// <summary>
        ///  获取分页列表数据
        /// </summary>
        /// <param name="keyword"></param>
        /// <param name="msgType"></param>
        /// <param name="currentPage"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        public string GetPageList(string name, int currentPage, int pageSize)
        {
            //数据量少的，直接查全部数据分页展示           
            List<EmployeeModel> list = idao.GetList(string.Empty);
            int totalCount = list.Count;
            //如果传入条件参数
            if (!string.IsNullOrEmpty(name))
            {
                list = list.Where(n => n.UserName.Contains(name)).OrderByDescending(n=>n.AID).Skip((currentPage - 1) * pageSize).Take(pageSize).ToList();
            }
            else
            {
                list = list.OrderByDescending(n => n.AID).Skip((currentPage - 1) * pageSize).Take(pageSize).ToList();
            }

            string jsonResult = JsonConvert.SerializeObject(list, new IsoDateTimeConverter());
            jsonResult = "{\"total\":" + totalCount + "," + "\"data\":" + jsonResult + "}";
            return jsonResult;
        }

        public ActionResult Show()
        {
            string ID = Request.QueryString["ID"];
            if (string.IsNullOrEmpty(ID))
            {
                return Redirect(Request.RawUrl);
            }
            int modelID = int.Parse(ID);
            EmployeeModel model = idao.GetModel(modelID);
            InitSelect(model.Role_ID);
            //只保留 二级菜单
            return View(model);
        }

        public ActionResult Create()
        {
            // 查询角色数据
            InitSelect(0);
            return View();
        }

        private void InitSelect(int selectID)
        {
            //加载产品类型
            List<RoleModel> selectItems = irole.GetList(string.Empty);
            List<SelectListItem> selectTypes = new List<SelectListItem>();
            selectTypes.Add(new SelectListItem() { Value = "0", Text = "请选择" });
            foreach (RoleModel item in selectItems)
            {
                if (item.AID == selectID)
                {
                    selectTypes.Add(new SelectListItem() { Value = item.AID.ToString(), Text = item.RoleName, Selected = true });
                }
                else
                {
                    selectTypes.Add(new SelectListItem() { Value = item.AID.ToString(), Text = item.RoleName });
                }
            }
            ViewData["selRole_ID"] = selectTypes;
        }

        [LogFilter("保存账户信息",OperateLogTypeEnum.操作日志,"Action")]
        public ActionResult Save(FormCollection form)
        {
            string action = Request.QueryString["Action"];
            string result = string.Empty;

            EmployeeModel model = new EmployeeModel();
            TryUpdateModel(model);
            model.Creator = CurrentUser.UserName;
            result = SaveStateEnum.OK.ToString();
            try
            {
                if (action == ActionEnum.Create.ToString())
                {
                    if (!idao.Exists(model.UserName))
                    {
                        model.Password = FormsAuthentication.HashPasswordForStoringInConfigFile("888888", "MD5");
                        idao.Add(model);
                    }
                    else
                    {
                        result = "用户名已经存在了";
                    }
                }
                else if (action == ActionEnum.Update.ToString())
                {
                    EmployeeModel editModel = idao.GetModel(model.AID);
                    editModel.LastUpdateDate = model.LastUpdateDate;
                    editModel.RealName = model.RealName;
                    editModel.Role_ID = model.Role_ID;
                    editModel.Phone = model.Phone;
                    editModel.Creator = model.Creator;
                    idao.Update(editModel);
                }
                else
                {
                    result = SaveStateEnum.NO.ToString();
                }

            }
            catch (Exception ex)
            {
                LogHelper.Error(ex, "数据{0}失败", action);
                result = SaveStateEnum.NO.ToString();
            }

            return Content(result);
        }

        public ActionResult Delete(string IDs)
        {
            string result = SaveStateEnum.NO.ToString();
            try
            {
                if (!string.IsNullOrEmpty(IDs))
                {
                    IDs = IDs.TrimEnd(',');
                    idao.DeleteList(IDs);
                    result = SaveStateEnum.OK.ToString();
                }
            }
            catch (Exception ex)
            {
                LogHelper.Error(ex, "删除数据失败!");
            }
            return Content(result);
        }

        [AcceptVerbs(HttpVerbs.Get)]
        public ActionResult ChangePassword()
        {
            ViewBag.UserName = CurrentUser.UserName;
            return View();
        }

         [ActionName("ChangePassword"), AcceptVerbs(HttpVerbs.Post)]
         [LogFilter("修改密码")]
        public JsonResult SavePwd(string userName, string oldPwd, string newPwd, string newPwd2)
        {
            EmployeeModel model = idao.GetModel(userName);
            if (model == null)
            {
                return Json(new { code = SaveStateEnum.NO.ToString(), msg = "账户不存在" });
            }
            oldPwd = FormsAuthentication.HashPasswordForStoringInConfigFile(oldPwd.Trim(), "MD5");
            if (oldPwd != model.Password)
            {
                return Json(new { code = SaveStateEnum.NO.ToString(), msg = "原密码不正确" });
            }
            if (newPwd != newPwd2)
            {
                return Json(new { code = SaveStateEnum.NO.ToString(), msg = "两次新密码输入不一致" }); 
            }
            newPwd = FormsAuthentication.HashPasswordForStoringInConfigFile(newPwd.Trim(), "MD5");
            model.Password = newPwd;
            model.LastUpdateDate = DateTime.Now;
            model.Creator = CurrentUser.UserName;
            if (idao.Update(model))
            {
                return Json(new { code = SaveStateEnum.OK.ToString(), msg = "修改成功" });
            }
            else
            {
                return Json(new { code = SaveStateEnum.NO.ToString(), msg = "修改失败，请稍后重试!" }); 
            }
        }
    }
}

